#  单元措施经济评价计算
#  tb_year_dvpunit_oilstimulate_evaluate_result表
import base64
import os
from fastapi.encoders import jsonable_encoder
from fastapi import APIRouter, Form, Depends
from starlette.requests import Request

from backend.app.app.api.api_v1.user import verify_token_user
from backend.app.app.api.calculation.unit_calculate import welloprcost, grosssalesincome, totaltax, staticgains, \
    stimnpv, stimroi, stimnpvr, stimfirr, increoilcritical, oilpricecritical
from backend.app.app.models.evaluate_calculate import Oil_Sale_TotalTax, Oil_Opr_Cost, Output_Page_Data, \
    Save_table_data, Save_Data_Private, User_Proj_page, Input_Data, Userproj_Oilstimeval, Save_Userproj_Curve_Data, \
    Return_Data
from backend.app.app.crud_pro.tb_calculate import get_alldata, table_store, table_store_private, \
    save_page1_data, save_page2_data, save_page3_data, get_evaluate_result, return_page1_data, return_page2_data, \
    return_page3_data, return_tb_userproj_dvpunit_oilstimeval_out, return_tb_userproj_dvpunit_oilstimeval_out_byfilter, \
    save_userproj_oilstimeval, return_userproj_oilstimeval, save_data_in_input, return_userproj_curve_data, \
    save_userproj_curve_data

from starlette.templating import Jinja2Templates
from docx import Document
import time

templates = Jinja2Templates(directory="templates")
calculate_router = APIRouter(prefix="/eva_cul", tags=["单元措施经济评价计算"])


# 存储图片到word文档
@calculate_router.post("/save_word", name="存储到word文档")
async def save_word(picture_data, ver=Depends(verify_token_user)):
    local_time = time.strftime("%Y-%m-%d", time.localtime())
    # 用base64生成图片
    data = base64.b64decode(picture_data)
    pic_name = local_time
    file = open('./{}.jpg'.format(pic_name), 'wb')
    file.write(data)
    file.close()
    # 生成word文件将图片存入
    document = Document()
    file_name = './{}.jpg'.format(local_time)
    document.add_picture(file_name)

    m = 0
    while True:
        if os.path.exists('./word{}.docx'.format(str(m) + '_' + str(local_time))) is True:  # 说明这个word已经创建
            m = m + 1
            continue
        else:
            document.save('./word{}.docx'.format(str(m) + '_' + str(local_time)))
            break

    # 删除生成图片文件
    os.remove("{}".format(file_name))
    return {"result": "true", "verify": ver}


@calculate_router.post("/main", name="表格初始界面")
async def eva_cul_main(ver=Depends(verify_token_user)):
    result_data = get_alldata()
    return {"result": result_data, "verify": ver}


@calculate_router.post("/output_page_data", name="输出数据界面表格界面")  # 此时是填入数据并计算后的界面
async def output_data_page(output_page_data: Output_Page_Data, ver=Depends(verify_token_user)):
    # 平均增油操作成本
    WellOprCost = welloprcost(output_page_data.increoil, output_page_data.oiloprcost)
    # 平均增油毛收入
    GrossSalesIncome = grosssalesincome(output_page_data.increoil, output_page_data.oilprice,
                                        output_page_data.oilcommodityratio)
    # 平均销售税费
    TotalTax = totaltax(GrossSalesIncome, output_page_data.totaltaxratio)
    # 平均静态收益
    StaticGains = staticgains(GrossSalesIncome, output_page_data.stimcost, WellOprCost, TotalTax)
    # 平均财务净现值
    StimNpv = stimnpv(output_page_data.increoil, output_page_data.validperiod, output_page_data.oilcommodityratio,
                      output_page_data.oilprice, output_page_data.totaltaxratio, output_page_data.oiloprcost,
                      output_page_data.discount, output_page_data.stimcost)
    # 投资利润率
    StimROI = stimroi(StaticGains, output_page_data.stimcost)
    # 财务净现值率
    StimNPVRV = stimnpvr(StimNpv, output_page_data.stimcost)
    # 财务内部收益率
    StimFirr = stimfirr(StaticGains, output_page_data.stimcost, output_page_data.validperiod)
    # 平均经济临界增油量
    IncreOilCritical = increoilcritical(output_page_data.validperiod, output_page_data.stimcost,
                                        output_page_data.discount, output_page_data.oilprice,
                                        output_page_data.oilcommodityratio, output_page_data.totaltaxratio,
                                        output_page_data.oiloprcost)
    # 平均经济临界油价
    OilPriceCritical = oilpricecritical(output_page_data.discount, output_page_data.validperiod,
                                        output_page_data.stimcost, output_page_data.increoil,
                                        output_page_data.oiloprcost,
                                        output_page_data.oilcommodityratio, output_page_data.totaltaxratio)

    return {"result1": WellOprCost, "result2": GrossSalesIncome, "result3": TotalTax, "result4": StaticGains,
            "result5": StimNpv, "result6": StimROI, "result7": StimNPVRV, "result8": StimFirr,
            "result9": IncreOilCritical,
            "result10": OilPriceCritical, "verify": ver}


@calculate_router.post("/save_data", name="存储数据界面")
async def output_data_page(save_table_data: Save_table_data, save_data_private: Save_Data_Private,
                           ver=Depends(verify_token_user)):
    try:
        a = table_store(dvpunit_name=save_table_data.DvpUnit_Name,
                        year=save_table_data.Year,
                        stimtype_name=save_table_data.StimType_Name,
                        stim_wellnumber_valid=save_table_data.Stim_WellNumber_Valid,
                        stim_wellvalidratio=save_table_data.Stim_WellValidRatio,
                        stim_validperiod_average=save_table_data.Stim_ValidPeriod_Average,
                        stim_increoil_average=save_table_data.Stim_IncreOil_Average,
                        stimcost_average=save_table_data.StimCost_Average,
                        oil_oprcost=save_table_data.Oil_OprCost,
                        oil_price=save_table_data.Oil_Price,
                        stimoil_commodityratio=save_table_data.StimOil_CommodityRatio,
                        oilsale_totaltaxratio=save_table_data.OilSale_TotalTaxRatio,
                        money_discount=save_table_data.Money_Discount,
                        remark=save_table_data.Remark,
                        stimoil_welloprcost_average=save_table_data.StimOil_WellOprCost_Average,
                        stimoil_total_taxratio_average=save_table_data.StimOil_Total_TaxRatio_Average,
                        stimoil_gross_salesincome_average=save_table_data.StimOil_Gross_SalesIncome_Average,
                        stimoil_static_gains_average=save_table_data.StimOil_Static_Gains_Average,
                        stimoil_npv_average=save_table_data.StimOil_NPV_Average,
                        stimoil_roi=save_table_data.StimOil_ROI,
                        stimoil_npvr=save_table_data.StimOil_NPVR,
                        stimoil_firr=save_table_data.StimOil_FIRR,
                        stim_increoil_critical_average=save_table_data.Stim_IncreOil_Critical_Average,
                        stimoil_price_critical=save_table_data.StimOil_Price_Critical)

        b = table_store_private(user_id=save_data_private.User_ID,
                                proj_id=save_data_private.Proj_ID,
                                dvpunit_name=save_data_private.DvpUnit_Name,
                                year=save_data_private.Year,
                                stimtype_name=save_data_private.StimType_Name,
                                stim_wellnumber_valid=save_data_private.Stim_WellNumber_Valid,
                                stim_wellvalidratio=save_data_private.Stim_WellValidRatio,
                                stim_validperiod_average=save_data_private.Stim_ValidPeriod_Average,
                                stim_increoil_average=save_data_private.Stim_IncreOil_Average,
                                stimcost_average=save_data_private.StimCost_Average,
                                oil_oprcost=save_data_private.Oil_OprCost,
                                oil_price=save_data_private.Oil_Price,
                                stimoil_commodityratio=save_data_private.StimOil_CommodityRatio,
                                oilsale_totaltaxratio=save_data_private.OilSale_TotalTaxRatio,
                                money_discount=save_data_private.Money_Discount,
                                remark=save_data_private.Remark,
                                stimoil_welloprcost_average=save_data_private.StimOil_WellOprCost_Average,
                                stimoil_total_tax_average=save_data_private.StimOil_Total_TaxRatio_Average,
                                stimoil_gross_salesincome_average=save_data_private.StimOil_Gross_SalesIncome_Average,
                                stimoil_static_gains_average=save_data_private.StimOil_Static_Gains_Average,
                                stimoil_npv_average=save_data_private.StimOil_NPV_Average,
                                stimoil_roi=save_data_private.StimOil_ROI,
                                stimoil_npvr=save_data_private.StimOil_NPVR,
                                stimoil_firr=save_data_private.StimOil_FIRR,
                                stim_increoil_critical_average=save_data_private.Stim_IncreOil_Critical_Average,
                                stimoil_price_critical=save_data_private.StimOil_Price_Critical)
        print('储存成功')
        return {"result1": a, "result2": b, "verify": ver}
    except:
        return False


# 存储用户第一界面数据及设置信息
@calculate_router.post("/user_proj_page1", name="用户第一页面数据")
async def proj_page1(user_proj_page: User_Proj_page, page_data=None, filter_data=None, set_info=None, picture1=None,
                     picture2=None, picture3=None, ver=Depends(verify_token_user)):
    try:
        a = save_page1_data(user_id=user_proj_page.User_ID,
                            proj_id=user_proj_page.Proj_ID,
                            remake=user_proj_page.Ramake,
                            page_data=page_data,
                            filter_data=filter_data,
                            set_info=set_info,
                            picture1=picture1,
                            picture2=picture2,
                            picture3=picture3
                            )
        return {"result": a, "verify": ver}
    except:
        return False


"""
    async def save_data(input_data: data_save, ver=Depends(verify_token_user)):

        u_id = get_u_id()
        p_id = get_p_id()
        list_u = []
        list_p = []
        for i in range(len(u_id)):
            list_u.append(u_id[i][0])
            list_p.append(p_id[i][0])
        if input_data.User_ID in list_u:
            if input_data.Proj_ID in list_p:
                result_up = updata_project_db(s_data=input_data)
                return {"result_save": result_up, "verify": ver}
                # for j in range(1,len(list_p)):
                #     if int(list_p[j]) - int(list_p[j-1]) != 1:
                #         id = int(list_p[j-1]) + 1
                #         input_data.Proj_ID = str(id)
                #         break
                # if j+1 == len(list_p):
                #     input_data.Proj_ID = str(j+2)
            else:
                result_add_o = save_project_db(s_data=input_data)

                return {"result_save": result_add_o, "verify": ver}
        else:
            result_add_o = save_project_db(s_data=input_data)
            return {"result_save": result_add_o, "verify": ver}

"""


# 存储用户第二界面数据及设置信息
@calculate_router.post("/user_proj_page2", name="用户第二页面数据")
async def proj_page2(user_proj_page: User_Proj_page, page_data=None, filter_data=None, set_info=None, picture1=None,
                     picture2=None, picture3=None, ver=Depends(verify_token_user)):
    try:
        a = save_page2_data(user_id=user_proj_page.User_ID,
                            proj_id=user_proj_page.Proj_ID,
                            remake=user_proj_page.Ramake,
                            page_data=page_data,
                            filter_data=filter_data,
                            set_info=set_info,
                            picture1=picture1,
                            picture2=picture2,
                            picture3=picture3
                            )
        return {"result": a, "verify": ver}
    except:
        return False


# 存储用户第三界面数据及设置信息
@calculate_router.post("/user_proj_page3", name="用户第三页面数据")
async def proj_page3(user_proj_page: User_Proj_page, page_data=None, filter_data=None, set_info=None, picture1=None,
                     picture2=None, picture3=None, ver=Depends(verify_token_user)):
    try:
        a = save_page3_data(user_id=user_proj_page.User_ID,
                            proj_id=user_proj_page.Proj_ID,
                            remake=user_proj_page.Ramake,
                            page_data=page_data,
                            filter_data=filter_data,
                            set_info=set_info,
                            picture1=picture1,
                            picture2=picture2,
                            picture3=picture3
                            )
        return {"result": a, "verify": ver}
    except:
        return False


# 返回第一页面存储的数据库数据
@calculate_router.post("/return_user_proj_page1", name="返回用户第一页面数据")
async def return_proj_page1(user_proj_page: User_Proj_page, ver=Depends(verify_token_user)):
    try:
        data = return_page1_data(user_id=user_proj_page.User_ID,
                                 proj_id=user_proj_page.Proj_ID)
        return {"result": data, "verify": ver}
    except:
        return False


# 返回第二页面存储的数据库数据
@calculate_router.post("/return_user_proj_page2", name="返回用户第二页面数据")
async def return_proj_page2(user_proj_page: User_Proj_page, ver=Depends(verify_token_user)):
    try:
        data = return_page2_data(user_id=user_proj_page.User_ID,
                                 proj_id=user_proj_page.Proj_ID)
        return {"result": data, "verify": ver}
    except:
        return False


# 返回第三页面存储的数据库数据
@calculate_router.post("/return_user_proj_page3", name="返回用户第三页面数据")
async def return_proj_page3(user_proj_page: User_Proj_page, ver=Depends(verify_token_user)):
    try:
        data = return_page3_data(user_id=user_proj_page.User_ID,
                                 proj_id=user_proj_page.Proj_ID)
        return {"result": data, "verify": ver}
    except:
        return False


# 返回开发单元年度油井措施经济评价结果表数据
@calculate_router.post("/return_tb_year_dvpunit_oilstimulate_evaluate_result",name="返回开发单元年度油井措施经济评价结果表")
async def return_evaluate_result(ver=Depends(verify_token_user)):
    try:
        return_data = get_evaluate_result()
        return {"result": return_data, "verify": ver}
    except:
        return False


# 返回用户工程单元经济评价计算功能输出结果表
@calculate_router.post("/return_tb_userproj_dvpunit_oilstimeval_out",name="返回用户工程单元经济评价计算功能输出结果表")
async def return_tb_out_data(ver=Depends(verify_token_user)):
    try:
        return_data = return_tb_userproj_dvpunit_oilstimeval_out()
        return {"result": return_data, "verify": ver}
    except:
        return False


# 根据用户名工程名返回用户工程单元经济评价计算功能输出结果表筛选信息 tb_userproj_dvpunit_oilstimeval_out
@calculate_router.post("/def return_tb_userproj_dvpunit_oilstimeval_out_byfilter",name="返回用户工程单元经济评价计算功能输出结果表筛选信息")
async def return_tb_out_data_byfilter(user_id, proj_id, ver=Depends(verify_token_user)):
    try:
        return_data = return_tb_userproj_dvpunit_oilstimeval_out_byfilter(user_id=user_id,
                                                                          proj_id=proj_id)
        return {"result": return_data, "verify": ver}
    except:
        return False


# 将用户工程单元经济评价计算功能输入数据表数据存入数据库 tb_userproj_dvpunit_oilstimeval_input
@calculate_router.post("/def save_data_tb_input",name="将用户工程单元经济评价计算功能输入数据表数据存入数据库")
async def save_data_in_tb_input(input_data: Input_Data, ver=Depends(verify_token_user)):
    try:
        a = save_data_in_input(user_id=input_data.User_ID,
                               proj_id=input_data.Proj_ID,
                               dvpunit_name=input_data.DvpUnit_Name,
                               year=input_data.Year,
                               stimtype_name=input_data.StimType_Name,
                               stim_wellnumber_valid=input_data.Stim_WellNumber_Valid,
                               stim_wellvalidratio=input_data.Stim_WellValidRatio,
                               stim_validperiod_average=input_data.Stim_ValidPeriod_Average,
                               stim_increoil_average=input_data.Stim_IncreOil_Average,
                               stimoil_commodityratio=input_data.StimOil_CommodityRatio,
                               oil_price=input_data.Oil_Price,
                               oilsale_totaltaxratio=input_data.OilSale_TotalTaxRatio,
                               money_discount=input_data.Money_Discount,
                               oil_oprcost=input_data.Oil_OprCost,
                               stimcost_average=input_data.StimCost_Average,
                               remark=input_data.Remark)

        return {"result": a, "verify": ver}
        # return True
    except:
        return False


# 保存数据至存储计算表格数据恢复表
@calculate_router.post("/save_userproj_oilstimeval",name="保存数据至存储计算表格数据恢复表")
async def save_data_userproj_oilstimeval(userproj_oilstimeval: Userproj_Oilstimeval, ver=Depends(verify_token_user)):
    try:
        a = save_userproj_oilstimeval(
            userproj_oilstimeval.User_ID,
            userproj_oilstimeval.Proj_ID,
            userproj_oilstimeval.inputdata,
            userproj_oilstimeval.output,
            userproj_oilstimeval.Data
        )
        # return True
        return {"result": a, "verify": ver}
    except:
        return False


# 从存储计算表格数据恢复表返回数据
@calculate_router.post("/return_userproj_oilstimeval",name="从存储计算表格数据恢复表返回数据")
async def return_data_userproj_oilstimeval(userproj_oilstimeval: Return_Data, ver=Depends(verify_token_user)):
    try:
        a = return_userproj_oilstimeval(userproj_oilstimeval.User_ID,userproj_oilstimeval.Proj_ID)
        return {"result": a, "verify": ver}
    except:
        return False


# 存储用户曲线图信息恢复表
@calculate_router.post("/save_userproj_curve_data",name="保存数据至用户曲线图信息恢复表")
async def save_userproj_curve(save_data: Save_Userproj_Curve_Data, ver=Depends(verify_token_user)):
    try:
        a = save_userproj_curve_data(user_id=save_data.User_ID,
                                     proj_id=save_data.Proj_ID,
                                     curve_data=save_data.Curve_Data)

        return {"result": a, "verify": ver}
    except:
        return False


# 从存储用户曲线图信息恢复表返回数据
@calculate_router.post("/return_userproj_curve_data",name="从用户曲线图信息恢复表返回数据")
async def return_userproj_curve(return_data: Return_Data, ver=Depends(verify_token_user)):
    try:
        a = return_userproj_curve_data(user_id=return_data.User_ID,
                                       proj_id=return_data.Proj_ID)

        return {"result": a, "verify": ver}
    except:
        return False
